package com.example.sharesinfo.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.NewContentBean;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.GlideHelper;
import com.example.sharesinfo.manager.UserManager;
import com.example.sharesinfo.model.FocusModel;
import com.example.sharesinfo.model.NewsCommentsModel;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.utils.TimeUtils;
import com.example.sharesinfo.view.InputTextMsgDialog;
import com.google.gson.Gson;

import org.json.JSONException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;

public class NewsInfoActivity extends BaseUIActivity implements View.OnClickListener {

    /**
     * 我时间转化类有问题
     * 新闻来源头像现在是用户头像代替的，后面要改回去
     * 关注这里新闻来源得有id，关注不仅仅是用户对用户
     * 可以在跳转到该页面前请求用弹框加载，处理数据页面的跳动/直接显示加载，加载完毕后显示页面
     * 评论用户加头像,点赞数量，相对应的回复
     */
    private NewContentBean mNews;
    private String newsId;
    private String userId;
    private String LogTag = "NewsInfoActivity:";
    //计时
    private static final int H_TIME_WHAT = 1000;
    private ImageButton ib_back;
    private TextView mTvNewsTitle;
    private CircleImageView mNewsHeadImage;
    private TextView mTvNewsUsername;
    private TextView mTvNewsTime;
    private TextView mTvNewsReadNumber;
    private TextView mTvNewsContent;
    private LinearLayout mLlPraise;
    private ImageView mIvPraise;
    private TextView mTvPraiseNumber;
    //处理回调的新闻数据
    private NewContentBean result;
    private int praiseNum;
    //关键字
    private LinearLayout ll_add;
    //评论 RecyclerView
    private RecyclerView mvNewsCommentsView;
    private CommonAdapter<NewsCommentsModel> mNewsCommentsAdapter;
    private List<NewsCommentsModel> mList = new ArrayList<>();
    private Button btn_send_comment;
    private InputTextMsgDialog inputTextMsgDialog;
    //点赞和取消
    //TalkId=***&UserId=***
    private String SendNewsCommentPraise = "http://119.23.221.142/api/information/SendNewsCommentPraise?";
    private Map<String, String> praiseDatas = new HashMap<>();
    //TalkId=***&UserId=***
    private String CancelNewsCommentPraise = "http://119.23.221.142/api/information/CancelNewsCommentPraise?";
    private Map<String, String> CancelPraiseDatas = new HashMap<>();
    //看新闻时间
    private int callTimer = 0;

    public static void startActivity(Context mContext, NewContentBean news) {
        Intent intent = new Intent(mContext, NewsInfoActivity.class);
        intent.putExtra("news", news);
        mContext.startActivity(intent);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case H_TIME_WHAT:
                    callTimer++;
                    LogUtils.i("看新闻时间" + callTimer + "秒");
                    if (callTimer == 30) {
                        AddGoldCoin();
                        callTimer = 0;
                    }
                    mHandler.sendEmptyMessageDelayed(H_TIME_WHAT, 1000);
                    break;
                case 200:
                    result = (NewContentBean) msg.obj;
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    mList.addAll(result.getNewsCommentsData());
                    mNewsCommentsAdapter.notifyDataSetChanged();
                    mTvNewsTitle.setText(result.getTitle());
                    //此处替换为新闻,新闻为默认头像
//                    String headImageUrl = SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, "");
//                    LogUtils.i(headImageUrl);
//                    GlideHelper.loadUrl(NewsInfoActivity.this, headImageUrl,  );
                    mTvNewsUsername.setText(result.getSource());
                    mTvNewsTime.setText(result.getIssueTime());
                    mTvNewsReadNumber.setText(result.getReadNumber() + "人已阅读");
                    mTvNewsContent.setText(result.getContent());
                    praiseNum = Integer.parseInt(result.getPraiseNumber());
                    mTvPraiseNumber.setText(result.getPraiseNumber());
                    if (result.getIf_Praise().equals("True")) {
                        mIvPraise.setImageResource(R.drawable.praise_checked);
                        mIvPraise.setTag("checked");
                    } else {
                        mIvPraise.setImageResource(R.drawable.praise_unchecked);
                        mIvPraise.setTag("unchecked");
                    }

                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    /**
     * 增加金币（参数为 UserId）增加金币
     */
    private void AddGoldCoin() {
        String urlRoot = "http:/119.23.221.142/api/user/AddGoldCoin?";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i("看新闻时间" + "金币+1");
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_body);
        initView();
        initData();
        //开始计时
        mHandler.sendEmptyMessage(H_TIME_WHAT);
        //关闭计时
        // mHandler.removeMessages(H_TIME_WHAT);
    }

    private void initData() {
        if (mList.size() > 0) {
            mList.clear();
        }
        mList.addAll(mNews.getNewsCommentsData());
        mNewsCommentsAdapter.notifyDataSetChanged();
        mTvNewsTitle.setText(mNews.getTitle());
        //此处替换为新闻
//        String headImageUrl = SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, "");
//        LogUtils.i(headImageUrl);
//        GlideHelper.loadUrl(NewsInfoActivity.this, headImageUrl, mNewsHeadImage);
        mTvNewsUsername.setText(mNews.getSource());
        mTvNewsTime.setText(mNews.getIssueTime());
        mTvNewsReadNumber.setText(mNews.getReadNumber() + "人已阅读");
        mTvNewsContent.setText(mNews.getContent());
        praiseNum = Integer.parseInt(mNews.getPraiseNumber());
        mTvPraiseNumber.setText(mNews.getPraiseNumber());
        if (mNews.getIf_Praise().equals("True")) {
            mIvPraise.setImageResource(R.drawable.praise_checked);
            mIvPraise.setTag("checked");
        } else {
            mIvPraise.setImageResource(R.drawable.praise_unchecked);
            mIvPraise.setTag("unchecked");
        }
        for (int i = 0; i < mNews.getKeywordsData().size(); i++) {
            Add(mNews.getKeywordsData().get(i));
        }
    }


    private void initView() {
        ib_back = findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        mNews = (NewContentBean) getIntent().getSerializableExtra("news");
        newsId = String.valueOf(mNews.getId());
        userId = SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        mTvNewsTitle = findViewById(R.id.tv_news_title);
        mNewsHeadImage = findViewById(R.id.news_head_image);
        mTvNewsUsername = findViewById(R.id.tv_news_username);
        mTvNewsTime = findViewById(R.id.tv_news_time);
        mTvNewsReadNumber = findViewById(R.id.tv_news_read_number);
        mTvNewsContent = findViewById(R.id.tv_news_content);
        ll_add = findViewById(R.id.ll_add);
        mLlPraise = findViewById(R.id.ll_news_praise);
        mLlPraise.setOnClickListener(this);
        mIvPraise = findViewById(R.id.iv_news_praised);
        mTvPraiseNumber = findViewById(R.id.tv_new_praise_number);
        mvNewsCommentsView = findViewById(R.id.mNewsCommentsView);
        mvNewsCommentsView.setLayoutManager(new LinearLayoutManager(this));
        mvNewsCommentsView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        mvNewsCommentsView.setFocusable(false);
        mNewsCommentsAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<NewsCommentsModel>() {
            @Override
            public void onBindViewHolder(final NewsCommentsModel model, final CommonViewHolder viewHolder, int type, int position) {
                final ImageView praised = viewHolder.getView(R.id.iv_news_comment_praised);
                if (praiseDatas.size() > 0) {
                    praiseDatas.clear();
                }
                if (CancelPraiseDatas.size() > 0) {
                    CancelPraiseDatas.clear();
                }
                if (!model.getComment_If_Praise().equals("False")) {
                    praised.setImageResource(R.drawable.praise_checked);
                    praised.setTag("checked");
                }
                final int[] praise = {Integer.parseInt(model.getComment_PraiseNumber())};
                praised.setOnClickListener(new View.OnClickListener() {
                    //点赞事件
                    @Override
                    public void onClick(View v) {
                        if (praised.getTag().equals("unchecked")) {
                            praised.setImageResource(R.drawable.praise_checked);
                            praise[0] += 1;
                            viewHolder.setText(R.id.tv_news_comment_praise_num, "" + praise[0]);
                            praised.setTag("checked");
                            //TalkId=***&UserId=***
                            praiseDatas.put("NewsCommentId", String.valueOf(model.getId()));
                            praiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(SendNewsCommentPraise, null,
                                    praiseDatas, null, null,
                                    new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "点赞失败");
                                        }
                                    });
                        } else if (praised.getTag().equals("checked")) {
                            LogUtils.i("点赞事件处理" + "取消点赞");
                            praised.setImageResource(R.drawable.praise_unchecked);
                            praise[0] -= 1;
                            viewHolder.setText(R.id.tv_news_comment_praise_num, "" + praise[0]);
                            praised.setTag("unchecked");
                            //TalkId=***&UserId=***
                            CancelPraiseDatas.put("NewsCommentId", String.valueOf(model.getId()));
                            CancelPraiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(CancelNewsCommentPraise, null,
                                    CancelPraiseDatas, null, null, new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "取消点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "取消点赞失败");
                                        }
                                    });

                        }
                    }
                });
                viewHolder.setImageUrl(NewsInfoActivity.this, R.id.tv_comment_head, model.getImageUrl());
                viewHolder.getView(R.id.tv_comment_head).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtils.i("用户id：" + model.getUserId());
                        UserManager.getInstance().queryUserInfo(model.getUserId(), NewsInfoActivity.this);
                    }
                });

                viewHolder.setText(R.id.news_body_comments_name, model.getCommenter());
                viewHolder.setText(R.id.news_body_comments_stock_age, model.getStockAge());
                viewHolder.setText(R.id.news_body_comments_content, model.getPoint());
                viewHolder.setText(R.id.news_body_comments_time, model.getCommentTime());
                viewHolder.setText(R.id.tv_news_comment_praise_num, model.getComment_PraiseNumber());
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.news_body_comments_list_item;
            }

        });
        mvNewsCommentsView.setAdapter(mNewsCommentsAdapter);

        btn_send_comment = findViewById(R.id.news_body_comment_box_btn);
        btn_send_comment.setOnClickListener(this);
        inputTextMsgDialog = new InputTextMsgDialog(this, R.style.customdialogstyle);
        inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
            @Override
            public void onTextSend(String msg) {
                LogUtils.i(LogTag + msg);
                addComment(msg);
                Toast.makeText(NewsInfoActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                queryDatas();
            }
        });
    }

    private void queryDatas() {
        String url = "http://119.23.221.142/api/information/GetNewsDetail?NewsId="
                + newsId + "&UserId=" + userId;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LogTag + s);
                NewContentBean bean = new Gson().fromJson(s, NewContentBean.class);
                message.what = code;
                message.obj = bean;
                LogUtils.i(LogTag + bean.getTitle());
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    private void addComment(String msg) {
        String url = "http://119.23.221.142/api/information/SendNewsComment?" +
                "NewsId=" + newsId + "&UserId=" + userId + "&Point=" + msg;
        OkHttpUtils.getInstance().Post(url, null, null, null, null,
                new OkHttpUtils.okHttpListener() {
                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i(LogTag + s);
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });
    }

    /**
     * 动态添加textView
     */
    private void Add(String text) {
        TextView textView = new TextView(getApplicationContext());
        textView.setBackgroundResource(R.drawable.news_body_keyword_bg);
        textView.setTextColor(getResources().getColor(R.color.cyanine));
        textView.setText("#" + text);
        textView.setTextSize(13);
        //设置包裹内容或者填充父窗体大小
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        //设置padding值
        textView.setPadding(9, 6, 9, 6);
        //设置margin值
        lp.setMargins(12, 0, 0, 0);
        ll_add.addView(textView, lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_news_praise:
                if (mIvPraise.getTag().equals("unchecked")) {
                    mIvPraise.setImageResource(R.drawable.praise_checked);
                    mIvPraise.setTag("checked");
                    praiseNum += 1;
                    mTvPraiseNumber.setText(String.valueOf(praiseNum));
                    String sendPraiseUrl = "http://119.23.221.142/api/information/SendNewsPraise?" +
                            "NewsId=" + newsId + "&UserId=" + userId;
                    LogUtils.i(LogTag + userId);
                    OkHttpUtils.getInstance().Post(sendPraiseUrl, null, null, null, null,
                            new OkHttpUtils.okHttpListener() {
                                @Override
                                public void OnSuccess(String s, int code) throws JSONException {
                                    LogUtils.i(LogTag + s);
                                }

                                @Override
                                public void OnFailed(String s) {
                                }
                            });

                } else {
                    mIvPraise.setImageResource(R.drawable.praise_unchecked);
                    mIvPraise.setTag("unchecked");
                    praiseNum -= 1;
                    mTvPraiseNumber.setText(String.valueOf(praiseNum));
                    String sendPraiseUrl = "http://119.23.221.142/api/information/CancelPraise?" +
                            "NewsId=" + newsId + "&UserId=" + userId;
                    LogUtils.i(LogTag + userId);
                    OkHttpUtils.getInstance().Post(sendPraiseUrl, null, null, null, null,
                            new OkHttpUtils.okHttpListener() {
                                @Override
                                public void OnSuccess(String s, int code) throws JSONException {
                                    LogUtils.i(LogTag + s);
                                }

                                @Override
                                public void OnFailed(String s) {
                                }
                            });
                }
                break;
            case R.id.news_body_comment_box_btn:
                inputTextMsgDialog.show();
                break;
            case R.id.ib_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(H_TIME_WHAT);
    }
}
